package zack.project.trigger.listener;

import zack.project.domain.activity.model.entity.DeliveryOrderEntity;
import zack.project.domain.activity.service.IRaffleActivityAccountQuotaService;
import zack.project.domain.credit.event.CreditAdjustSuccessMessageEvent;
import zack.project.types.enums.ResponseCode;
import zack.project.types.event.BaseEvent;
import zack.project.types.exception.AppException;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;


@Slf4j
@Component
public class CreditAdjustSuccessCustomer {

    @Value("${spring.rabbitmq.topic.credit_adjust_success}")
    private String topic;
    @Resource
    private IRaffleActivityAccountQuotaService raffleActivityAccountQuotaService;

    /**
     * 监听CreditRepository.saveUserCreditTradeOrder发送的消息
     * @param message
     */
    @RabbitListener(queuesToDeclare = @Queue(value = "${spring.rabbitmq.topic.credit_adjust_success}"))
    public void listener(String message) {
        try {

            BaseEvent.EventMessage<CreditAdjustSuccessMessageEvent.CreditAdjustSuccessMessage> eventMessage = JSON.parseObject(message, new TypeReference<BaseEvent.EventMessage<CreditAdjustSuccessMessageEvent.CreditAdjustSuccessMessage>>() {
            }.getType());
            //获取积分调额成功的消息内容
            CreditAdjustSuccessMessageEvent.CreditAdjustSuccessMessage creditAdjustSuccessMessage =
                    eventMessage.getData();

            //积分兑换sku消耗的积分扣减对该账户的积分账户的积分调整成功，
            // 需要将兑换抽奖次数或行为返利产生的充值单(对应数据库表{raffle_activity_order})的状态调整为completed
            // 并调整用户抽奖次数(对应数据库表{raffle_activity_account}，{raffle_activity_account_day}，
            // {raffle_activity_account_month})
            DeliveryOrderEntity deliveryOrderEntity = new DeliveryOrderEntity();
            deliveryOrderEntity.setUserId(creditAdjustSuccessMessage.getUserId());
            deliveryOrderEntity.setOutBusinessNo(creditAdjustSuccessMessage.getOutBusinessNo());
            raffleActivityAccountQuotaService.updateOrder(deliveryOrderEntity);
            log.info("监听积分账户调整成功消息，交易商品发货完成 topic: {} message: {}", topic, message);
        } catch (AppException e) {
            if (ResponseCode.INDEX_DUP.getCode().equals(e.getCode())) {
                log.warn("监听积分账户调整成功消息，进行交易商品发货，消费重复 topic: {} message: {}", topic, message, e);
                return;
            }
            throw e;
        } catch (Exception e) {
            log.error("监听积分账户调整成功消息，进行交易商品发货失败 topic: {} message: {}", topic, message, e);
            throw e;
        }
    }

}
